//utf-8

//选择合约

function toAddContract(){
	
	var dialogStruct={
			'display':contextRootPath+'/tCMmContract/prepareExecute/toSelectContractBuy',
			'width':720,
			'height':600,
			'title':'选择合约',
			'isIframe':'false',
			'buttons':[
			           {'text':'确定','action':doAddFromContractSure,'isClose':true},
			  		   {'text':'关闭','isClose':true}
			]
		};
		
		var dialogAdd =jyDialog(dialogStruct).open();

	
}

//增加债权
function toAddDataCredit(){
	var obj  = $('#cooperorgCode').length;
	var value;
	if(obj>0){
		value = $('#cooperorgCode').val();
	}else {
		value = $('#dtocooperorgCode').val();
	}
	
	if(value=="" || null ==value){
		alert("请选择载入合约信息！");
		return;
	}
	var creditPackageWrite = $("#dealPackage").val();
	if(creditPackageWrite==null||creditPackageWrite==""){
		alert("请选择或者输入债权包信息！");
		return;
	}
	var statementDateStart = $("#statementDateStart").val();
	var statementDateEnd = $("#statementDateEnd").val();
	var publicRepayType = $("#publicRepayType").val();
	var bdDate = $('#bdDate').val();
	if(null==statementDateStart || ""==statementDateStart){
		alert("请选择账单起始日！");
		return;
	}
	
	if(null==statementDateEnd || ""==statementDateEnd){
		alert("请选择账单结束日！");
		return;
	}
	
	if(statementDateStart>statementDateEnd){
		alert("账单起始日不能大于账单结束日！");
		return;
	}
	
	if(null==publicRepayType || ""==publicRepayType){
		alert("请选择还款方式！");
		return;
	}
	/*if(null==bdDate || ""==bdDate){
		alert("请选着标的日期！");
		return;
	}*/
	var dialogStruct={
			'display':contextRootPath+'/creditBuy/prepareExecute/toAddCreditBuy',
			'width':1100,
			'height':600,
			'title':'债权列表',
			'isIframe':'false',
			'buttons':[
			         {'text':'确定','action':doAddCreditBuy,'isClose':true},
			  		 {'text':'关闭','isClose':true}
			]
		};
		
		var dialogAdd =jyDialog(dialogStruct).open();
}

//确认债权
function doAddCreditBuy(obj){
	var table=iframeCredit.iframeObj["table"];
	var ids ,transferIds,thisMakeCreditorValues;
	var isAuto = $('input[name=isAuto]:checked').val();
	if(isAuto==null||isAuto==""||isAuto=="N"){
		//不需要自动匹配
		ids = table.getSelectedObjs("id");
		if(ids==''){
			alert("请从债权列表勾选债权明显！");
			return;
		}
		ids = "" + ids;
		transferIds = table.getSelectedObjs("transferId");
		transferIds = "" + transferIds;
		thisMakeCreditorValues = table.getSelectedObjs("thisMakeCreditorValue");
		thisMakeCreditorValues = "" + thisMakeCreditorValues;
		
		if(thisMakeCreditorValues=='' ){
			alert("您选择的债权明细数据的“本次转让债权价”存在空值!");
			return;
		}
		
		if(ids=='' || transferIds=='' || thisMakeCreditorValues=='' ){
			alert("您选择的债权明细数据存在空值");
			return;
		}
		isAuto="N";
	}else if(isAuto=="Y"){
		var totalRows = table.totalRows;
		if(!totalRows>0){
			alert("债权列表数据为空，不能进行操作！");
			return ;
		}
	}
	
	
	var cooperorgCode = $('#dtocooperorgCode').val();
	var valueContractCode = $('#dtocontractCode').val();
	var valueAgreementCode = $('#dtoagreementCode').val();
	var dealType = $('#dealType').val();
	var dealCode = $('#dealCode').val();
	var settleDealCodes = $('#settleDealCodes').val();
	var planSellSum = $('#planSellSum').val();
	var practicalSellSum = $('#practicalSellSum').val();
	
	var id = $('#idValue').val();
	var creditPackageName = $('#dealPackage').val();
	var statementDateStart = $('#statementDateStart').val();
	var statementDateEnd = $('#statementDateEnd').val();
	var publicRepayType = $('#publicRepayType').val();
	var productType = $('#productType').val();
	var addOrUpdate = $('#addOrUpdate').val();
	var bdDate = $('#bdDate').val();
	var dataUrl =contextRootPath + "/secondBuyCredit/insertOrUpdateCreditBuy";	
	
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"autoOptionCreditType":isAuto,
			"sumCreditValue":practicalSellSum,
			"transferIds":transferIds,
			"thisMakeCreditorValues":thisMakeCreditorValues,
			"ids":ids,
			"dealCode":dealCode,
			"contractCode":valueContractCode,
			"argeementCode":valueAgreementCode,
			"cooperorgCode":cooperorgCode,
			"id":id,
			"settleDealCodes":settleDealCodes,
			"dealType":dealType,
			"addOrUpdate":addOrUpdate,
			"packageNum":creditPackageName,
			"billDate":statementDateStart,
			"billDateEnd":statementDateEnd,
			"repayType":publicRepayType,
			"productType":productType,
			"planSellSum":planSellSum,
			"practicalSellSum":practicalSellSum,
			"creditReferDate":bdDate
			},
		success: function(results) {
			if(results.status=="ok"){
				var obj = results.data;
				$("#idValue").val(obj.id);
				$("#dealCode").val(obj.dealCode);
				initFnCreditDetailView(transferIds);
				$("#creditDetailTable").show();
				CreditValueSum();
				$("#isDelete").val("true");
				$('#dealPackage').attr("disabled","disabled");
				$('#statementDateStart').attr("disabled","disabled");
				$('#statementDateEnd').attr("disabled","disabled");
				$('#publicRepayType').attr("disabled","disabled");
			}else {
				alert("确认债权失败：" + results.msg);
			}
			
		}
	});
}

//债权价值合计
function CreditValueSum(){
	var dealCode = $("#dealCode").val();
	var dataUrl =contextRootPath + "/cooperorgDeal/getDealDetailByCreditSumTotal";
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"dealCode":dealCode},
		error: function(result) {
			
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			$("#detialNumber").val(obj.detialNumber);
			$("#sumCreditorValue").val(obj.sumCreditorValue);
		}
	});
}

//确认合约
function doAddFromContractSure(){
	var contractCode = iframeSelectContract.iframeObj["table"].getSelectedObjs("contractCode");
	var settleDealCodes = $('#settleDealCodes').val();
    var planSellSum = $('#planSellSum').val();
    var practicalSellSum = $('#practicalSellSum').val();
    var cooperorgCode = $("#cooperorgCode").val();
	window.location=contextRootPath+"/creditBuy/prepareExecute/toDeal?contractCode="+contractCode+"&cooperorgCode="+cooperorgCode+"&settleDealCodes="+settleDealCodes+"&planSellSum="+planSellSum+"&practicalSellSum="+practicalSellSum;
	// window.location = contextRootPath+'/tCMmContract/prepareExecute/toBackCooperorgDealAdd?contractCode='+contractCode;
	
}
//双击合约
function doAddFromContract(contractCode){
	var settleDealCodes = $('#settleDealCodes').val();
    var planSellSum = $('#planSellSum').val();
    var practicalSellSum = $('#practicalSellSum').val();
    var cooperorgCode = $("#cooperorgCode").val();
	window.location=contextRootPath+"/creditBuy/prepareExecute/toDeal?contractCode="+contractCode+"&cooperorgCode="+cooperorgCode+"&settleDealCodes="+settleDealCodes+"&planSellSum="+planSellSum+"&practicalSellSum="+practicalSellSum;
	// window.location = contextRootPath+'/tCMmContract/prepareExecute/toBackCooperorgDealAdd?contractCode='+contractCode;
	
}

//返回合约
function returnContract(contractCode){
	
	var dataUrl =contextRootPath + "/tCMmContract/returnContract";	
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"contractCode":contractCode},
		error: function(result) {
			
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			if(obj[0].length<0){
				return;
			}
			var creditorAffirmRule = obj[0].cdto.creditorAffirmRule;
			var dealType = obj[0].cdto.dealType;
			if(creditorAffirmRule=='01'){
				$("#dtocreditorAffirmRule").attr("value","发起方");
			}else if(creditorAffirmRule=='02'){
				$("#dtocreditorAffirmRule").attr("value","接收方");
			}
			$("#creditorAffirmRule").attr("value",dealType);
		}
	});
}

function selectStyle(){
	var cooperorgCode = $('#dtocooperorgCode').val();
	var contractCode = $('#dtocontractCode').val();
	if(cooperorgCode!="" && null !=cooperorgCode){
		$("select[name=cooperorgCode]").find("option[value='" + cooperorgCode + "']").attr("selected",true);
		$("select[name=contractCode]").find("option[value='" + contractCode + "']").attr("selected",true);
	}
}

function isShowCooperorg(){
	$("#creditRestrainTitle").show();
	$("#creditRestrainTitleValue").show();
	$("#creditOperation").show();
	$("#creditDetailOperation").show();
}

function isShowContract(){
	$("#creditPackageColumn").show();
	searchCreditPackage();
}

//查询债权包隐藏标签
var selectOptions=[];
function searchCreditPackage(selectID,updatePackageValue,type){

	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var valueContractCode = $('#dtocontractCode').val();
	var dataUrl = contextRootPath + '/cooperorgDeal/getPackageListByAll?cooperorgCode=' + valueCooperorgCode +'&contractCode='+valueContractCode;//+ "&pagType=" + cimsConstant.CREDIT_RESOURCE
	$('#creditPackage').html("<option id='selectValue' value='-1'>请选择</option>");
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:'',
		success: function(results) {
			var result=results.data;
			var j;
			var resultLength = result.length - 1;
			for (j = 0; j <= resultLength; j++) {
				$('#creditPackage').append("<option name='"+result[j].creditPackageName+"' value='"+result[j].billDate+":"+result[j].billDateEnd+":"+result[j].repayType + "'>"+result[j].creditPackageName+"</option>");
				selectOptions.push(result[j].creditPackageName);
			}
			completePackage(selectOptions,selectID,updatePackageValue,type);
		}
	});

}

//保存交易流水
function saveDealBuy(){
	
	var obj  = $('#cooperorgCode').length;
	var valueCooperorgCode;
	if(obj>0){
		valueCooperorgCode = $('#cooperorgCode').val();
	}else {
		valueCooperorgCode = $('#dtocooperorgCode').val();
	}
	
	var obj  = $('#contractCode').length;
	var valueContractCode;
	if(obj>0){
		valueContractCode = $('#contractCode').val();
	}else {
		valueContractCode = $('#dtocontractCode').val();
	}
	
	var creditPackageName = $('#dealPackage').val();
	var dealCode = $('#dealCode').val();
	var id = $('#idValue').val();
	var sumCreditorValue = $('#sumCreditorValue').val();
	var detialNumber = $('#detialNumber').val();
	var dealType = $('#dealType').val();
	var dtoagreementCode = $('#dtoagreementCode').val();
	var statementDateStart = $('#statementDateStart').val();
	var statementDateEnd = $('#statementDateEnd').val();
	var publicRepayType = $('#publicRepayType').val();
	var productType = $('#productType').val();
	
	if(null==dealType || ""==dealType){
		alert("请选择交易类型！");
		return;
	}
	if(null==valueCooperorgCode ||""==valueCooperorgCode){
		alert("请选择合作机构！");
		return;
	}
	
	
	if(valueContractCode!=null && valueContractCode!=""){
		if(null==creditPackageName ||""==creditPackageName){
			alert("请选择或者填写包名！");
			return;
		}
		
		if(null==statementDateStart || ""==statementDateStart){
			alert("请选择账单起始日！");
			return;
		}
		
		if(null==statementDateEnd || ""==statementDateEnd){
			alert("请选择账单结束日！");
			return;
		}
		
		if(statementDateStart>statementDateEnd){
			alert("账单起始日不能大于账单结束日！");
			return;
		}
		
		if(null==publicRepayType || ""==publicRepayType){
			alert("请选择还款方式！");
			return;
		}
	}
	
	
	
	if(null==dealCode ||""==dealCode){
		alert("请选择债权！");
		return;
	}
		
	if(confirm("确认保存！")){
		var dataUrl =contextRootPath + "/secondBuyCredit/doSaveConfirm";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"cooperorgCode":valueCooperorgCode,
				  "contractCode":valueContractCode,
				  "creditPackageName":creditPackageName,
				  "billDate":statementDateStart,
				  "billDateEnd":statementDateEnd,
				  "repayType":publicRepayType,
				  "productType":productType,
				  "dealCode":dealCode,
				  "id":id,
				  "sumCreditorValue":sumCreditorValue,
				  "detialNumber":detialNumber,
				  "dealType":dealType,
				  "agreementCode":dtoagreementCode,
				  "billDate":statementDateStart,
				  "billDateEnd":statementDateEnd},
			success: function(results) {
				$("#isDeleteAndIsExport").val("true");
				$("#dealPackage").attr("disabled","disabled");
				$("#statementDateStart").attr("disabled","disabled");
				$("#statementDateEnd").attr("disabled","disabled");
				$("#publicRepayType").attr("disabled","disabled");
				try{
					var winObj = parent.tabs.getTabWinByTitle("二次购买");
					if(winObj)
					winObj.location.reload();
				}catch(e){
				
				}finally{
					alert("保存成功！");
				}
				
			}
			});
		}
	
}


function saveCreditDealBuy(){
	var dealCode = $('#dealCode').val();
	if(null==dealCode ||""==dealCode){
		alert("请选择债权！");
		return;
	}
	
	var dataUrl =contextRootPath + "/tCMmCreditDealDetail/queryListTCMmCreditDealDetail?dealStreamCode=" + dealCode;
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:'',
		error: function(result) {
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var result=results.data;
			var resultLength = result.length;
			if(resultLength<=0){
				alert("该交易下没有债权！");
			}else {
				saveDealBuy();
			}
		}
	});
}

//试算
function settleCreditDeal(){
	var dealCode = $('#dealCode').val();
	
	if(null==dealCode || ""==dealCode){
		alert("请先导入债权确认信息！");
		return;
	}
	
	if(confirm("请确认导入的债权信息!")){
		var dataUrl =contextRootPath + "/settle/testSettleCooperorgDeal";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"dealCode":dealCode},
			error: function(result) {
				alert("请查看返回数据是否正确：" + result);
			},
			success: function(results) {
				
			}
		});
	}
}

//选择债权包
function creditPackageOperation(obj){
	var text = obj.value;
	var selectObj = $("#creditPackage option[name="+obj.value+"]").length;
	var textValue = "" + $("#creditPackage option[name="+obj.value+"]").val();
	
	
	if (selectObj!=0){
			var textValueArray = textValue.split(":");
			$("#statementDateStart").val(textValueArray[0]);
			$("#statementDateEnd").val(textValueArray[1]);
			$("#publicRepayType option[value="+textValueArray[2]+"]").attr("selected","true");
			$('#publicRepayType').attr("disabled","disabled");
			$('#statementDateStart').attr("disabled","disabled");
			$('#statementDateEnd').attr("disabled","disabled");
	}else {
		$('#publicRepayType').removeAttr("disabled");
		$('#statementDateStart').removeAttr("disabled");
		$('#statementDateEnd').removeAttr("disabled");
		$("#statementDateStart").val("");
		$("#statementDateEnd").val("");
	}
	
}
//根据输入的债权包selete自动订到已有
function creditPackageOperationWrite(obj){
	
	var valueWrite = obj.value;
	$("#creditPackage option[name='"+valueWrite+"']").attr("selected","true");
	var value = $("#creditPackage option[name='"+valueWrite+"']").val();
	
	
	if(-1==value){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#creditPackage option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').removeAttr("disabled");
		$("#creditPackageWrite").val("");
		
	}else if (value=="1"){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#statementDate option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').attr("disabled","disabled");

	}else if(value=="16"){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#statementDate option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').attr("disabled","disabled");
	}else{
		$('#statementDate').removeAttr("disabled");
	}
	
}
//删除债权
function deleteCredit(){
	var table=iframeCreditView.iframeObj["table"];
	var dealCode = $('#dealCode').val();
	var transferIds = table.getSelectedObjs("transferId");
	transferIds = transferIds + "";
	var v_ids = iframeCreditView.iframeObj["table"].getSelectedIds().join(",");
	//如果没有选中 数据则
	if(v_ids == ""){
		alert("请选择待删除的数据！");
		return;
	}
	if(confirm("您确认要删除选择的数据吗？")){
        $.ajax({
            type:"POST",
            dataType : "json",
            url:contextRootPath+"/cooperorgDeal/deleteDetailByCredit",
            data:{
            	"dealCode":dealCode, 
            	"transferIds":transferIds
            	},
            error: function(result) {
            	CreditValueSum();
    			},
            success:function(msg){
            	alert(msg.msg);
            	var v_status = msg.status;
            	//删除成功后
            	if(v_status.indexOf('ok') >-1){
            		iframeCreditView.iframeObj["table"].removeSelectedRow();
            		CreditValueSum();
            	}	
            }
        });
    }
}


/*function packageDay(url){
	
	 $.ajax({
         type:"get",
         dataType : "json",
         url:url,
         success:function(msg){
         	
        	 
         	
         	
         }
     });
}*/

//页面关闭按钮操作
function closeFather(){
	var winObj = parent.tabs.getTabWinByTitle("债权交易");
	if(null==winObj){
		parent.tabs.close();
	}else{
		winObj.location.reload();
		parent.tabs.close();
	}
	
}

function sumSelectValue(){
	var thisMakeCreditorValues = iframeCredit.iframeObj["table"].getSelectedObjs("thisMakeCreditorValue");
	var thisMakeCreditorValueLength = thisMakeCreditorValues.length;
	var i;
	var selectedCreditValue = $("#sumCreditorValue").val();
	if(selectedCreditValue==null||selectedCreditValue==""){
		selectedCreditValue = "0";
	}
	selectedCreditValue  = parseFloat(selectedCreditValue);
	var thisMakeCreditorValue;
	if(thisMakeCreditorValueLength>0){
		for(i=0;i<thisMakeCreditorValueLength;i++){
			thisMakeCreditorValue =parseFloat(thisMakeCreditorValues[i]);
			selectedCreditValue  += thisMakeCreditorValue;
		}
		selectedCreditValue = selectedCreditValue.toFixed(2);
		$("#selectedCreditValue").val(selectedCreditValue);
	}else{
		var sumCreditorValue = $("#sumCreditorValue").val();
		if(sumCreditorValue==null||sumCreditorValue==""){
				$("#selectedCreditValue").val(0);
		}else{
				$("#selectedCreditValue").val(sumCreditorValue);
		}
	}
	
}
function confirmBuyCreditDetail(){
	var dtocooperorgCode = $('#dtocooperorgCode').val();
	var dealCode = $('#dealCode').val();
	var repaymentAffiliation = $("#repaymentAffiliation").val();
	var contractCode = $("#dtocontractCode").val();
	var txtHtml = $("#repaymentAffiliation").find("option:selected").text();
	if(null==dealCode ||""==dealCode){
		alert("请确认交易流水号是否存在！");
		return;
	}
	if(null==repaymentAffiliation||""==repaymentAffiliation){
		alert("月还归属不能为空！");
		return;
	}
	if(confirm("确认购买？月还归属为【"+txtHtml+"】确定吗？")){
		var dataUrl =contextRootPath + "/secondBuyCredit/doConfirmSecondBuyCredit";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"dealCode":dealCode,"cooperorgCode":dtocooperorgCode,"repaymentAffiliation":repaymentAffiliation,"contractCode":contractCode},
			error: function(result) {
				alert("请查看返回数据是否正确：" + result.msg);
			},
			success: function(results) {
				alert(results.msg);
			}
			});
		}
}
$(document).ready(function(){
	$('#creditorAffirmRule').attr("disabled","disabled");
});

